package cn.melon.view;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JLabel;

/**
 * @ClassName: JCircleLabel
 * @author Hzy
 * 继承JLabel的写的控件，一个圆形的图片容器，可设置大小和图片路径。
 */
public class JCircleLabel extends JLabel{
	private int radius;
	private BufferedImage headImg;
	
	public JCircleLabel(int radius,String imgPath){
		super();
		this.radius = radius;
//		this.setPreferredSize(new Dimension(2*radius,2*radius));
		try{
		    File img = new File(imgPath);
			headImg = ImageIO.read(this.getClass().getResource(imgPath));
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	@Override
	protected void paintComponent(Graphics g){
		Graphics2D g2d = (Graphics2D) g;
//		g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);;
//		设置控件的边界为圆形

		Ellipse2D.Double c = new Ellipse2D.Double(0,0,2*radius+1,2*radius+1);
		g2d.setClip(c);
//		绘制头像
		g2d.drawImage(headImg, 0, 0, 2*radius, 2*radius, null);
		super.paintComponent(g);
	}
	
	@Override
	protected void paintBorder(Graphics g){
//		绘制边框
		g.setColor(Color.blue);
		Graphics2D g2d = (Graphics2D) g;
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//开启抗锯齿
		g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);//渲染质量高
		g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);//关闭抖动
		g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);//画笔控制
//		g2d.drawOval(0,0,2*radius,2*radius);
//		在clip范围之外画边界会让圆形十分圆滑，原因待考
//		g2d.drawOval(0,0,2*radius+1,2*radius+1);
		g2d.drawOval(0,0,2*radius+2,2*radius+2);
	}
}
